import BackPage from '@/components/BackPage';
import { addWrite, selectWriteById, updateWrite } from '@/services/write';
import { colorStr } from '@/utils/utils';
import { Button, Form, Input, message, Modal } from 'antd';
import BraftEditor from 'braft-editor';
import 'braft-editor/dist/index.css';
import React, { useCallback, useEffect, useState } from 'react';
import { history } from 'umi';
import styles from './index.less';

const { TextArea } = Input;

const AddAdvice: React.FC = ({}) => {
  const [form] = Form.useForm();
  const { id }: any = history?.location?.query;
  let isEdit = !(id === '' || id === undefined || !id);
  const [editorValue, setEditorValue] = useState<any>(BraftEditor.createEditorState('<p></p>'));

  const select = useCallback(async () => {
    if (isEdit) {
      try {
        await selectWriteById({ id: id }).then((res) => {
          form.setFieldsValue({ title: res[0].title, detail: res.detail });
          setEditorValue(BraftEditor.createEditorState(res[0].detail));
        });
      } catch (error) {
        console.log(error);
      }
    }
  }, [form, id, isEdit]);

  useEffect(() => {
    select();
  }, [select]);

  // 拿到form表单里面富文本的值
  const normFile = (e: any) => {
    return e.toHTML();
  };

  // 富文本handleChange
  const handleChange = (editorState: any) => {
    setEditorValue(editorState);
  };

  const confirmSubmit = async (values: any) => {
    try {
      if (isEdit) {
        await updateWrite(values).then(() => {
          form.resetFields();
          history.push('/notice');
          message.success('编辑资讯成功！');
        });
      } else {
        await addWrite(values).then(() => {
          message.success('新增资讯成功！');
          history.push('/notice');
        });
      }
    } catch (error) {
      console.log(error);
    }
  };

  const onFinish = async () => {
    let values = await form.validateFields();
    if (isEdit) {
      values.id = id;
    }

    if (values.detail === '' || values.detail === '<p></p>') {
      message.error('请输入资讯内容');
    } else {
      Modal.confirm({
        title: isEdit ? '编辑' : '新建',
        centered: true,
        content: '请确认文章是否无误',
        okText: '确认',
        cancelText: '取消',
        onOk: () => confirmSubmit(values),
      });
    }
  };

  return (
    <BackPage thisRoute={'/addAdvice'} lastRoute={'新增资讯'}>
      <div className={styles.addArticle}>
        <div className={styles.addArticleDetails}>
          <Form
            name="basic"
            initialValues={{ remember: true }}
            onFinish={onFinish}
            autoComplete="off"
            form={form}
          >
            <div className={styles.addArticleBody}>
              <div className={styles.addArticleBodyBacInput}>
                <div className={styles.addArticleBodyBacInputDiv}>
                  <Form.Item name="title" rules={[{ required: true, message: '请在这里输入标题' }]}>
                    <TextArea
                      placeholder="请在这里输入标题"
                      autoSize
                      showCount
                      maxLength={30}
                      onBlur={(e) => e}
                      style={{ width: '91%' }}
                      onPressEnter={(e) => e}
                    />
                  </Form.Item>
                </div>
                <div className={styles.addArticleBodyBacInputDiv2}>
                  <Form.Item name="author">
                    <Input bordered={false} disabled defaultValue={'作者：四季养生购物网站'} />
                  </Form.Item>
                </div>
                <div className={styles.addArticleBodyBacInputDiv3}>
                  <Form.Item
                    name="detail"
                    valuePropName="detail"
                    getValueFromEvent={normFile}
                    rules={[{ required: true }]}
                  >
                    <BraftEditor
                      value={editorValue}
                      onChange={handleChange}
                      placeholder="请输入资讯内容"
                    />
                  </Form.Item>
                </div>
              </div>
            </div>
          </Form>
        </div>
        <div className={styles.btn}>
          {isEdit ? (
            <Button
              className={styles.submit}
              style={{ color: colorStr(9), backgroundColor: colorStr(1) }}
              onClick={onFinish}
            >
              提交编辑
            </Button>
          ) : (
            <Button
              className={styles.submit}
              style={{ color: colorStr(9), backgroundColor: colorStr(1) }}
              onClick={onFinish}
            >
              新建
            </Button>
          )}
        </div>
      </div>
    </BackPage>
  );
};

export default AddAdvice;
